/*
Copyright 2024.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controller

import (
	"context"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	v2 "k8s.io/apimachinery/pkg/apis/meta/v1"
	cicv1 "schedulerNetAwareController/api/cic.io/v1"

	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"
)

// NodeTopoNetMetricRootReconciler reconciles a NodeTopoNetMetricRoot object
type NodeTopoNetMetricRootReconciler struct {
	client.Client
	Scheme *runtime.Scheme
}

// +kubebuilder:rbac:groups=cic.io,resources=nodetoponetmetricroots,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=cic.io,resources=nodetoponetmetricroots/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=cic.io,resources=nodetoponetmetricroots/finalizers,verbs=update
// +kubebuilder:rbac:groups="",resources=nodes;pods,verbs=get;list;watch;delete

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the NodeTopoNetMetricRoot object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.18.2/pkg/reconcile
func (r *NodeTopoNetMetricRootReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	logger := log.FromContext(ctx)

	// TODO：
	// 创建了一个新的root后，为每个节点个创建一个metric资源
	var nodeTopoNetMetricRoot cicv1.NodeTopoNetMetricRoot
	if err := r.Get(ctx, req.NamespacedName, &nodeTopoNetMetricRoot); err != nil {
		if errors.IsNotFound(err) {
			logger.Info("删除NodeTopoNetMetricsRoot资源")
		} else {
			logger.Error(err, "未找到NodeTopoNetMetricRoot")
		}
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}
	nodeTopoNetMetricRootList := cicv1.NodeTopoNetMetricRootList{}
	if err := r.List(ctx, &nodeTopoNetMetricRootList, client.InNamespace(req.Namespace)); err != nil {
		logger.Error(err, "未找到NodeTopoNetMetricRootList")
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}

	if len(nodeTopoNetMetricRootList.Items) >= 1 {
		logger.Error(nil, "NodeTopoNetMetricRootList超过1，则本次不进行子资源生成", "len(Items)", len(nodeTopoNetMetricRootList.Items))
		return ctrl.Result{}, nil
	}
	if nodeTopoNetMetricRoot.ObjectMeta.Generation > 1 {
		// 资源非首次创建，可能是更新操作，直接跳过
		return ctrl.Result{}, nil
	}

	// 根据node数量生成子资源
	var nodeList v1.NodeList
	if err := r.List(ctx, &nodeList); err != nil {
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}

	nodeNameList := make([]string, 0)
	for _, node := range nodeList.Items {
		nodeNameList = append(nodeNameList, node.Name)
	}

	for _, node := range nodeList.Items {
		// 每个node创建一个NodeTopoNetMetric

		nodeMetrics := cicv1.NodeTopoNetMetric{}

		// nodeName的唯一性保证此项的唯一性，资源命名中不要带有下划线
		nodeMetrics.Name = node.Name + "-metric"
		//logger.Info("准备创建资源")
		nodeMetrics.Spec.NodeName = node.Name
		nodeMetrics.Namespace = NodeTopoNetMetricNamespace
		nodeMetrics.SetOwnerReferences([]v2.OwnerReference{
			*v2.NewControllerRef(&nodeTopoNetMetricRoot, cicv1.GroupVersion.WithKind("NodeTopoNetMetricRoot")),
		})

		latencyMetrics := make([]cicv1.LatencyToNode, 0)
		for _, name := range nodeNameList {
			if name != node.Name {
				toNode := cicv1.LatencyToNode{
					NodeName: name,
					Latency:  make([]string, 0),
				}
				latencyMetrics = append(latencyMetrics, toNode)
			}
		}
		nodeMetrics.Status.Latencies.LatencyMetrics = latencyMetrics

		if err := r.Create(ctx, &nodeMetrics); err != nil {
			logger.Error(err, "创建子资源NodeTopoNetMetric失败", "node", node.Name)
		}

		// status信息填充
		if err := r.Status().Update(ctx, &nodeMetrics); err != nil {
			logger.Error(err, "更新子资源NodeTopoNetMetric中的Status失败", "node", node.Name)
		}
	}

	return ctrl.Result{}, nil
}

// SetupWithManager sets up the controller with the Manager.
func (r *NodeTopoNetMetricRootReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&cicv1.NodeTopoNetMetricRoot{}).
		Complete(r)
}
